package com.gjy.pd.state;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-17 10:33:07
 */
public class Client {

    public static void main(String[] args) {
        AppContext appContext = new AppContext();
        appContext.favorite();
        appContext.comment("Hello");
    }

    private static abstract class UserState {
        protected AppContext appContext;

        public abstract void favorite();

        public abstract void comment(String comment);

        public void setAppContext(AppContext appContext) {
            this.appContext = appContext;
        }
    }

    private static class LoginState extends UserState {

        @Override
        public void favorite() {
            System.out.println("收藏成功");
        }

        @Override
        public void comment(String comment) {
            System.out.println(comment);
        }
    }

    private static class LogoutState extends UserState {

        @Override
        public void favorite() {
            login();
            appContext.getState().favorite();
        }

        @Override
        public void comment(String comment) {
            login();
            appContext.getState().comment(comment);
        }

        private void login() {
            System.out.println("跳转到登录界面");
            this.appContext.setCurrent(AppContext.LOGIN);
        }
    }

    private static class AppContext {
        private static final UserState LOGIN = new LoginState();
        private static final UserState LOGOUT = new LogoutState();

        private UserState current = LOGOUT;

        {
            LOGIN.setAppContext(this);
            LOGOUT.setAppContext(this);
        }

        public UserState getCurrent() {
            return current;
        }

        public void setCurrent(UserState current) {
            this.current = current;
            this.current.setAppContext(this);
        }

        public UserState getState() {
            return this.current;
        }

        public void favorite() {
            this.current.favorite();
        }

        public void comment(String comment) {
            this.current.comment(comment);
        }
    }
}
